#include "obj_wagon.h"

int obj_wagon::cloaded=0;	//class loaded
GLuint obj_wagon::wag_textures[WAG_NUM];
float obj_wagon::speed=10./RAIL_LENGHT;

obj_wagon::obj_wagon(){
	if (cloaded==0){
		char filename[100];
		for (int i=0;i<WAG_NUM;i++){
			sprintf(filename,"./media/objects/obj_wagon%d.tga",i);
			wag_textures[i]=load_tga_texture(filename);
			if (wag_textures[i]==(GLuint)-1){
				debug("Can't find right picture");
				return;
			}
		}
		cloaded=1;
	}
	
	rprogress=0;
	fprogress=1;
	rrto=rrfrom=rfto=rffrom=NULL;

	col_verts.resize(4);
	verts.resize(4);
	faces.resize(2);
	UVs.resize(4);
	
	verts[0][0]=-WAG_LENGHT/2.;verts[0][1]=-WAG_WIDTH/2.;verts[0][2]=0;
	verts[1][0]=+WAG_LENGHT/2.;verts[1][1]=-WAG_WIDTH/2.;verts[1][2]=0;
	verts[2][0]=+WAG_LENGHT/2.;verts[2][1]=+WAG_WIDTH/2.;verts[2][2]=0;
	verts[3][0]=-WAG_LENGHT/2.;verts[3][1]=+WAG_WIDTH/2.;verts[3][2]=0;

	faces[0][0]=0;faces[0][1]=1;faces[0][2]=2;faces[0][3]=0;faces[0][4]=1;faces[0][5]=2;
	faces[1][0]=0;faces[1][1]=2;faces[1][2]=3;faces[1][3]=0;faces[1][4]=2;faces[1][5]=3;

	UVs[0][0]=0;UVs[0][1]=0;
	UVs[1][0]=1;UVs[1][1]=0;
	UVs[2][0]=1;UVs[2][1]=1;
	UVs[3][0]=0;UVs[3][1]=1;
	
	loaded=1;
	transparent=1;
	calc_r();
	collide=1;
	obj_type=OBJ_TYPE_WAGON;
}

void obj_wagon::draw_wagon(){
	update_pos();
	draw();
}

void obj_wagon::update_pos (){
	oldx=x;
	oldy=y;
	oldrot=rot;
	fprogress+=speed*time_elapsed();
	rprogress+=speed*time_elapsed();
	while (fprogress>1){
		if (rfto->next!=NULL){
			rffrom=rfto;
			rfto=rfto->next;
		}
		else{
			fprogress=0;
			rprogress=0;
			debug("rto==NULL end of rails");
		}
		if (rfto==NULL){
			debug("rto==NULL end of rails");
			return;
		}
		fprogress-=1;
	}

	if (rfto==NULL){
		debug("rto==NULL end of rails");
		return;
	}

	while (rprogress>1){
		rrfrom=rrto;
		rrto=rrto->next;
		rprogress-=1;
	}
	
	x=rprogress*rrto->x+(1-rprogress)*rrfrom->x;
	y=rprogress*rrto->y+(1-rprogress)*rrfrom->y;
	xf=fprogress*rfto->x+(1-fprogress)*rffrom->x;
	yf=fprogress*rfto->y+(1-fprogress)*rffrom->y;
	
	rot=atan2(yf-y,xf-x);	//zrata uhol podla pozicie predku a zadku	
	
/*	if (type==WAG_LOCOMOTIVE)
		printf("r%f\tir%d\txr%f\tyr%f\tif%d\txf%f\tyf%f\tprogress%f\n",rot,rrfrom->index,x,y,rffrom->index,xf,yf,progress);
	if (type==WAG_LOCOMOTIVE)
		printf("atan(%f,%f)=%f\n",yf-y,xf-x,rot*180/M_PI);
*/	
	x+=cos (rot)*(WAG_LENGHT-1)/2.;
	y+=sin (rot)*(WAG_LENGHT-1)/2.;
	
	dx = (x-oldx)/time_elapsed();
	dy = (y-oldy)/time_elapsed();

	if (abs(rot-oldrot)>M_PI)	//atan2 mohol preskocit!!!
		if (rot<oldrot)
			drot = (2*M_PI+rot-oldrot)/time_elapsed();
		else
			drot = (rot-oldrot-2*M_PI)/time_elapsed();
	else
		drot = (rot-oldrot)/time_elapsed();
	
	calc_col_verts();
	
	if (dx>15||dy>15||drot>50){
		debug("%f \t%f \t%f",dx,dy,drot);
		debug("sleduj vlak!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
	}
}
